﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IPTools.Core;
using Microsoft.AspNetCore.Http;
using RxxAdmin.Common.Extensions;
using RxxAdmin.IServices;
using RxxAdmin.Model.Entity;
using RxxAdmin.Model.Logs;
using UAParser;

namespace RxxAdmin.Services;

public class LoginLogService : BaseServices<LoginLog>, ILoginLogService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public LoginLogService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
    public async Task<List<long>> Add(string name,string msg) {
        LoginLog loginLog = GetInfoByHttpContext(_httpContextAccessor.HttpContext);
        loginLog.LoginUser = name;
        loginLog.DateTime = DateTime.Now;
        loginLog.LogMsg = msg;
        return await AddSplit(loginLog);
    }
    public LoginLog GetInfoByHttpContext(HttpContext context)
    {
        ClientInfo GetClientInfo(HttpContext context)
        {
            var str = context.GetUserAgent();
            var uaParser = Parser.GetDefault();
            ClientInfo c;
            try
            {
                c = uaParser.Parse(str);
            }
            catch
            {
                c = new ClientInfo("null", new OS("null", "null", "null", "null", "null"), new Device("null", "null", "null"), new UserAgent("null", "null", "null", "null"));
            }
            return c;
        }
        var ipAddr = context.GetClientIp();
        IpInfo location;
        if (ipAddr == "127.0.0.1")
        {
            location = new IpInfo() { Province = "本地", City = "本机" };
        }
        else
        {
            try
            {
                location = IpTool.Search(ipAddr);
            }
            catch
            {
                location = new IpInfo() { Province = ipAddr, City = "未知地区" };
            }
        }
        ClientInfo clientInfo = GetClientInfo(context);
        LoginLog entity = new()
        {
            Browser = clientInfo.Device.Family,
            Os = clientInfo.OS.ToString(),
            LoginIp = ipAddr,
            LoginLocation = location.Province + "-" + location.City
        };
        return entity;
    }
}
